/*
 * contrib/btree_gist/btree_ts.c
 */
#include "postgres.h"

#include <limits.h>

#include "btree_gist.h"
#include "btree_utils_num.h"
#include "utils/builtins.h"
#include "utils/datetime.h"
#include "utils/float.h"

typedef struct
{
	Timestamp	lower;
	Timestamp	upper;
} tsKEY;

/*
** 时间戳操作
*/
PG_FUNCTION_INFO_V1(gbt_ts_compress);
PG_FUNCTION_INFO_V1(gbt_tstz_compress);
PG_FUNCTION_INFO_V1(gbt_ts_fetch);
PG_FUNCTION_INFO_V1(gbt_ts_union);
PG_FUNCTION_INFO_V1(gbt_ts_picksplit);
PG_FUNCTION_INFO_V1(gbt_ts_consistent);
PG_FUNCTION_INFO_V1(gbt_ts_distance);
PG_FUNCTION_INFO_V1(gbt_tstz_consistent);
PG_FUNCTION_INFO_V1(gbt_tstz_distance);
PG_FUNCTION_INFO_V1(gbt_ts_penalty);
PG_FUNCTION_INFO_V1(gbt_ts_same);


#ifdef USE_FLOAT8_BYVAL
#define TimestampGetDatumFast(X) TimestampGetDatum(X)
#else
#define TimestampGetDatumFast(X) PointerGetDatum(&(X))
#endif


static bool fc_gbt_tsgt(const void *fc_a, const void *fc_b, FmgrInfo *fc_flinfo)
{
	const Timestamp *fc_aa = (const Timestamp *) fc_a;
	const Timestamp *fc_bb = (const Timestamp *) fc_b;

	return DatumGetBool(DirectFunctionCall2(timestamp_gt,
											TimestampGetDatumFast(*fc_aa),
											TimestampGetDatumFast(*fc_bb)));
}

static bool fc_gbt_tsge(const void *fc_a, const void *fc_b, FmgrInfo *fc_flinfo)
{
	const Timestamp *fc_aa = (const Timestamp *) fc_a;
	const Timestamp *fc_bb = (const Timestamp *) fc_b;

	return DatumGetBool(DirectFunctionCall2(timestamp_ge,
											TimestampGetDatumFast(*fc_aa),
											TimestampGetDatumFast(*fc_bb)));
}

static bool fc_gbt_tseq(const void *fc_a, const void *fc_b, FmgrInfo *fc_flinfo)
{
	const Timestamp *fc_aa = (const Timestamp *) fc_a;
	const Timestamp *fc_bb = (const Timestamp *) fc_b;

	return DatumGetBool(DirectFunctionCall2(timestamp_eq,
											TimestampGetDatumFast(*fc_aa),
											TimestampGetDatumFast(*fc_bb)));
}

static bool fc_gbt_tsle(const void *fc_a, const void *fc_b, FmgrInfo *fc_flinfo)
{
	const Timestamp *fc_aa = (const Timestamp *) fc_a;
	const Timestamp *fc_bb = (const Timestamp *) fc_b;

	return DatumGetBool(DirectFunctionCall2(timestamp_le,
											TimestampGetDatumFast(*fc_aa),
											TimestampGetDatumFast(*fc_bb)));
}

static bool fc_gbt_tslt(const void *fc_a, const void *fc_b, FmgrInfo *fc_flinfo)
{
	const Timestamp *fc_aa = (const Timestamp *) fc_a;
	const Timestamp *fc_bb = (const Timestamp *) fc_b;

	return DatumGetBool(DirectFunctionCall2(timestamp_lt,
											TimestampGetDatumFast(*fc_aa),
											TimestampGetDatumFast(*fc_bb)));
}


static int fc_gbt_tskey_cmp(const void *fc_a, const void *fc_b, FmgrInfo *fc_flinfo)
{
	tsKEY	   *fc_ia = (tsKEY *) (((const Nsrt *) fc_a)->t);
	tsKEY	   *fc_ib = (tsKEY *) (((const Nsrt *) fc_b)->t);
	int			fc_res;

	fc_res = DatumGetInt32(DirectFunctionCall2(timestamp_cmp, TimestampGetDatumFast(fc_ia->lower), TimestampGetDatumFast(fc_ib->lower)));
	if (fc_res == 0)
		return DatumGetInt32(DirectFunctionCall2(timestamp_cmp, TimestampGetDatumFast(fc_ia->upper), TimestampGetDatumFast(fc_ib->upper)));

	return fc_res;
}

static float8 fc_gbt_ts_dist(const void *fc_a, const void *fc_b, FmgrInfo *fc_flinfo)
{
	const Timestamp *fc_aa = (const Timestamp *) fc_a;
	const Timestamp *fc_bb = (const Timestamp *) fc_b;
	Interval   *fc_i;

	if (TIMESTAMP_NOT_FINITE(*fc_aa) || TIMESTAMP_NOT_FINITE(*fc_bb))
		return get_float8_infinity();

	fc_i = DatumGetIntervalP(DirectFunctionCall2(timestamp_mi,
											  TimestampGetDatumFast(*fc_aa),
											  TimestampGetDatumFast(*fc_bb)));
	return (float8) Abs(INTERVAL_TO_SEC(fc_i));
}


static const gbtree_ninfo tinfo =
{
	gbt_t_ts,
	sizeof(Timestamp),
	16,							/* sizeof(gbtreekey16) */
	fc_gbt_tsgt,
	fc_gbt_tsge,
	fc_gbt_tseq,
	fc_gbt_tsle,
	fc_gbt_tslt,
	fc_gbt_tskey_cmp,
	fc_gbt_ts_dist
};


PG_FUNCTION_INFO_V1(ts_dist);
Datum ts_dist(PG_FUNCTION_ARGS)
{
	Timestamp	fc_a = PG_GETARG_TIMESTAMP(0);
	Timestamp	fc_b = PG_GETARG_TIMESTAMP(1);
	Interval   *fc_r;

	if (TIMESTAMP_NOT_FINITE(fc_a) || TIMESTAMP_NOT_FINITE(fc_b))
	{
		Interval   *fc_p = palloc(sizeof(Interval));

		fc_p->day = INT_MAX;
		fc_p->month = INT_MAX;
		fc_p->time = PG_INT64_MAX;
		PG_RETURN_INTERVAL_P(fc_p);
	}
	else
		fc_r = DatumGetIntervalP(DirectFunctionCall2(timestamp_mi,
												  PG_GETARG_DATUM(0),
												  PG_GETARG_DATUM(1)));
	PG_RETURN_INTERVAL_P(abs_interval(fc_r));
}

PG_FUNCTION_INFO_V1(tstz_dist);
Datum tstz_dist(PG_FUNCTION_ARGS)
{
	TimestampTz fc_a = PG_GETARG_TIMESTAMPTZ(0);
	TimestampTz fc_b = PG_GETARG_TIMESTAMPTZ(1);
	Interval   *fc_r;

	if (TIMESTAMP_NOT_FINITE(fc_a) || TIMESTAMP_NOT_FINITE(fc_b))
	{
		Interval   *fc_p = palloc(sizeof(Interval));

		fc_p->day = INT_MAX;
		fc_p->month = INT_MAX;
		fc_p->time = PG_INT64_MAX;
		PG_RETURN_INTERVAL_P(fc_p);
	}

	fc_r = DatumGetIntervalP(DirectFunctionCall2(timestamp_mi,
											  PG_GETARG_DATUM(0),
											  PG_GETARG_DATUM(1)));
	PG_RETURN_INTERVAL_P(abs_interval(fc_r));
}


/**************************************************
 * 时间戳操作
 **************************************************/


static inline Timestamp
fc_tstz_to_ts_gmt(TimestampTz fc_ts)
{
	/* 不需要时区修正，因为定义上GMT的偏移量为0 */
	return (Timestamp) fc_ts;
}


Datum gbt_ts_compress(PG_FUNCTION_ARGS)
{
	GISTENTRY  *fc_entry = (GISTENTRY *) PG_GETARG_POINTER(0);

	PG_RETURN_POINTER(gbt_num_compress(fc_entry, &tinfo));
}


Datum gbt_tstz_compress(PG_FUNCTION_ARGS)
{
	GISTENTRY  *fc_entry = (GISTENTRY *) PG_GETARG_POINTER(0);
	GISTENTRY  *fc_retval;

	if (fc_entry->leafkey)
	{
		tsKEY	   *fc_r = (tsKEY *) palloc(sizeof(tsKEY));
		TimestampTz fc_ts = DatumGetTimestampTz(fc_entry->key);
		Timestamp	fc_gmt;

		fc_gmt = fc_tstz_to_ts_gmt(fc_ts);

		fc_retval = palloc(sizeof(GISTENTRY));
		fc_r->lower = fc_r->upper = fc_gmt;
		gistentryinit(*fc_retval, PointerGetDatum(fc_r),
					  fc_entry->rel, fc_entry->page,
					  fc_entry->offset, false);
	}
	else
		fc_retval = fc_entry;

	PG_RETURN_POINTER(fc_retval);
}

Datum gbt_ts_fetch(PG_FUNCTION_ARGS)
{
	GISTENTRY  *fc_entry = (GISTENTRY *) PG_GETARG_POINTER(0);

	PG_RETURN_POINTER(gbt_num_fetch(fc_entry, &tinfo));
}

Datum gbt_ts_consistent(PG_FUNCTION_ARGS)
{
	GISTENTRY  *fc_entry = (GISTENTRY *) PG_GETARG_POINTER(0);
	Timestamp	fc_query = PG_GETARG_TIMESTAMP(1);
	StrategyNumber fc_strategy = (StrategyNumber) PG_GETARG_UINT16(2);

	/* Oid		subtype = PG_GETARG_OID(3); */
	bool	   *fc_recheck = (bool *) PG_GETARG_POINTER(4);
	tsKEY	   *fc_kkk = (tsKEY *) DatumGetPointer(fc_entry->key);
	GBT_NUMKEY_R fc_key;

	/* 由此函数服务的所有案例都是精确的 */
	*fc_recheck = false;

	fc_key.lower = (GBT_NUMKEY *) &fc_kkk->lower;
	fc_key.upper = (GBT_NUMKEY *) &fc_kkk->upper;

	PG_RETURN_BOOL(gbt_num_consistent(&fc_key, (void *) &fc_query, &fc_strategy,
									  GIST_LEAF(fc_entry), &tinfo, fcinfo->flinfo));
}

Datum gbt_ts_distance(PG_FUNCTION_ARGS)
{
	GISTENTRY  *fc_entry = (GISTENTRY *) PG_GETARG_POINTER(0);
	Timestamp	fc_query = PG_GETARG_TIMESTAMP(1);

	/* Oid		subtype = PG_GETARG_OID(3); */
	tsKEY	   *fc_kkk = (tsKEY *) DatumGetPointer(fc_entry->key);
	GBT_NUMKEY_R fc_key;

	fc_key.lower = (GBT_NUMKEY *) &fc_kkk->lower;
	fc_key.upper = (GBT_NUMKEY *) &fc_kkk->upper;

	PG_RETURN_FLOAT8(gbt_num_distance(&fc_key, (void *) &fc_query, GIST_LEAF(fc_entry),
									  &tinfo, fcinfo->flinfo));
}

Datum gbt_tstz_consistent(PG_FUNCTION_ARGS)
{
	GISTENTRY  *fc_entry = (GISTENTRY *) PG_GETARG_POINTER(0);
	TimestampTz fc_query = PG_GETARG_TIMESTAMPTZ(1);
	StrategyNumber fc_strategy = (StrategyNumber) PG_GETARG_UINT16(2);

	/* Oid		subtype = PG_GETARG_OID(3); */
	bool	   *fc_recheck = (bool *) PG_GETARG_POINTER(4);
	char	   *fc_kkk = (char *) DatumGetPointer(fc_entry->key);
	GBT_NUMKEY_R fc_key;
	Timestamp	fc_qqq;

	/* 由此函数服务的所有案例都是精确的 */
	*fc_recheck = false;

	fc_key.lower = (GBT_NUMKEY *) &fc_kkk[0];
	fc_key.upper = (GBT_NUMKEY *) &fc_kkk[MAXALIGN(tinfo.size)];
	fc_qqq = fc_tstz_to_ts_gmt(fc_query);

	PG_RETURN_BOOL(gbt_num_consistent(&fc_key, (void *) &fc_qqq, &fc_strategy,
									  GIST_LEAF(fc_entry), &tinfo, fcinfo->flinfo));
}

Datum gbt_tstz_distance(PG_FUNCTION_ARGS)
{
	GISTENTRY  *fc_entry = (GISTENTRY *) PG_GETARG_POINTER(0);
	TimestampTz fc_query = PG_GETARG_TIMESTAMPTZ(1);

	/* Oid		subtype = PG_GETARG_OID(3); */
	char	   *fc_kkk = (char *) DatumGetPointer(fc_entry->key);
	GBT_NUMKEY_R fc_key;
	Timestamp	fc_qqq;

	fc_key.lower = (GBT_NUMKEY *) &fc_kkk[0];
	fc_key.upper = (GBT_NUMKEY *) &fc_kkk[MAXALIGN(tinfo.size)];
	fc_qqq = fc_tstz_to_ts_gmt(fc_query);

	PG_RETURN_FLOAT8(gbt_num_distance(&fc_key, (void *) &fc_qqq, GIST_LEAF(fc_entry),
									  &tinfo, fcinfo->flinfo));
}


Datum gbt_ts_union(PG_FUNCTION_ARGS)
{
	GistEntryVector *fc_entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
	void	   *fc_out = palloc(sizeof(tsKEY));

	*(int *) PG_GETARG_POINTER(1) = sizeof(tsKEY);
	PG_RETURN_POINTER(gbt_num_union((void *) fc_out, fc_entryvec, &tinfo, fcinfo->flinfo));
}


#define penalty_check_max_float(val) \
	do { \
		if ( val > FLT_MAX ) \
				val = FLT_MAX; \
		if ( val < -FLT_MAX ) \
				val = -FLT_MAX; \
	} while (0)


Datum gbt_ts_penalty(PG_FUNCTION_ARGS)
{
	tsKEY	   *fc_origentry = (tsKEY *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(0))->key);
	tsKEY	   *fc_newentry = (tsKEY *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(1))->key);
	float	   *fc_result = (float *) PG_GETARG_POINTER(2);

	double		fc_orgdbl[2],
				fc_newdbl[2];

	/*
	 * 我们在这里始终使用“double”时间戳。精度应该足够好
	 */
	fc_orgdbl[0] = ((double) fc_origentry->lower);
	fc_orgdbl[1] = ((double) fc_origentry->upper);
	fc_newdbl[0] = ((double) fc_newentry->lower);
	fc_newdbl[1] = ((double) fc_newentry->upper);

	penalty_check_max_float(fc_orgdbl[0]);
	penalty_check_max_float(fc_orgdbl[1]);
	penalty_check_max_float(fc_newdbl[0]);
	penalty_check_max_float(fc_newdbl[1]);

	penalty_num(fc_result, fc_orgdbl[0], fc_orgdbl[1], fc_newdbl[0], fc_newdbl[1]);

	PG_RETURN_POINTER(fc_result);
}


Datum gbt_ts_picksplit(PG_FUNCTION_ARGS)
{
	PG_RETURN_POINTER(gbt_num_picksplit((GistEntryVector *) PG_GETARG_POINTER(0),
										(GIST_SPLITVEC *) PG_GETARG_POINTER(1),
										&tinfo, fcinfo->flinfo));
}

Datum gbt_ts_same(PG_FUNCTION_ARGS)
{
	tsKEY	   *fc_b1 = (tsKEY *) PG_GETARG_POINTER(0);
	tsKEY	   *fc_b2 = (tsKEY *) PG_GETARG_POINTER(1);
	bool	   *fc_result = (bool *) PG_GETARG_POINTER(2);

	*fc_result = gbt_num_same((void *) fc_b1, (void *) fc_b2, &tinfo, fcinfo->flinfo);
	PG_RETURN_POINTER(fc_result);
}
